/* eslint-disable react-hooks/rules-of-hooks */
import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { ProCard, ProTable, TableDropdown } from '@ant-design/pro-components';
import { Input, Tree, Avatar, Image, Space } from 'antd';
import { getDeptTreeList } from '@/services/api/setting/dept';
const { Search } = Input;
import styles from './style.less';
import { getListPage } from '@/services/api/setting/user';
import { buildParams } from '@/utils/paramUtils';
import { tableSuppert } from '@/utils/response';

export default function user() {
  // 组织架构树数据
  const [treeList, setTreeList] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [searchValue, setSearchValue] = useState('');
  //选中节点
  const [checkDeptId, setCheckDeptId] = useState(0);
  // 表格Ref
  const tableRef = useRef();
  // 发起网络请求
  const getDept = async () => {
    await getDeptTreeList().then((res) => {
      setTreeList(res.data);
    });
  };
  // 请求树形type
  useEffect(() => {
    getDept();
  }, []);

  // 展开
  const onExpand = (newExpandedKeys) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };
  // 高亮对象
  const loop = (data) =>
    data.map((item) => {
      const strTitle = item.title;
      const index = strTitle.indexOf(searchValue);
      const beforeStr = strTitle.substring(0, index);
      const afterStr = strTitle.slice(index + searchValue.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span className={styles.siteTreeSearchValue}>{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span>{strTitle}</span>
        );

      if (item.children) {
        return {
          title,
          key: item.key,
          parentId: item.parentId,
          selectable: item.selectable,
          sort: item.sort,
          children: loop(item.children),
        };
      }

      return {
        title,
        key: item.key,
        parentId: item.parentId,
        selectable: item.selectable,
        sort: item.sort,
      };
    });

  // 用于临时将转换非树数组
  const dataList = [];

  // 生成树
  const generateList = (data) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title, parentId, selectable, sort } = node;
      dataList.push({ key, title: title, parentId: parentId, selectable: selectable, sort: sort });
      if (node.children) {
        generateList(node.children);
      }
    }
  };

  // 调用生成
  generateList(treeList);

  // 获取父节点
  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  // 搜索
  const onChange = (e) => {
    let { value } = e.target;
    value = String(value).trim();
    if (value === '') {
      setExpandedKeys([]);
      setAutoExpandParent(false);
      setSearchValue('');
    }
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, treeList);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(true);
    setSearchValue(value);
  };

  const columns = [
    // {
    //   title: '#',
    //   dataIndex: 'index',
    //   valueType: 'indexBorder',
    //   hideInSearch: true,
    //   width: 48,
    // },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      hideInSearch: true,
      render: (text, record, index, action) => [
        <Avatar key="avatar" src={<Image src={text} width={35} />} />,
      ],
      width: 48,
    },
    {
      title: '账号',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      key: 'mobile',
      ellipsis: true,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      valueEnum: {
        0: {
          text: '男',
        },
        1: {
          text: '女',
        },
        2: {
          text: '未知',
        },
      },
    },
    {
      title: '用户类型',
      dataIndex: 'userType',
      key: 'userType',
      hideInTable: true,
      // hideInForm: true,
    },

    {
      title: '生日',
      dataIndex: 'birthday',
      key: 'birthday',
      ellipsis: true,
      hideInTable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '禁用',
          status: 'Error',
        },
      },
    },

    {
      title: '操作',
      key: 'action',
      hideInSearch: true,
      render: (text, record, index, action) => [
        <Space key="action">
          <a key="edit">编辑</a>
          <a key="rest">重置</a>
          {record.hasDel === '0' ? '' : <a key="delete1">删除</a>}
          <TableDropdown
            key="actionGroup"
            onSelect={() => action?.reload()}
            menus={[{ key: 'delete', name: '删除' }]}
          />
        </Space>,
      ],
    },
  ];

  return (
    <PageContainer content="系统组织架构用户列表">
      <ProCard split="vertical">
        <ProCard title="组织架构" colSpan="20%">
          <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={onChange} />
          <Tree
            key="tree"
            height={600}
            defaultExpandAll
            onSelect={(selectedKeys) => {
              console.log(selectedKeys);
              debugger;
              if (selectedKeys.length == 0) {
                setCheckDeptId(0);
              } else {
                setCheckDeptId(selectedKeys[0]);
              }
              tableRef.current.reload();
            }}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            treeData={loop(treeList)}
          />
        </ProCard>
        <ProCard title="用户">
          <ProTable
            // 关键key
            rowKey="id"
            actionRef={tableRef}
            // 聚焦加载 false
            revalidateOnFocus={false}
            // 等分每列
            tableLayout="fixed"
            // 分页配置
            pagination={{ defaultPageSize: 10, showQuickJumper: true }}
            // 选择
            rowSelection={{}}
            // 表头
            columns={columns}
            // 发请求
            request={async (param, sorter) => {
              // if (Object.keys(sorter).length === 0) {
              //   sorter.createTime = 'desc';
              // }
              // 设置选中节点，带条件查询
              param['deptId'] = parseInt(checkDeptId);
              const data = await getListPage(buildParams(param, sorter)).then((res) => {
                return res.data;
              });
              return tableSuppert(data);
            }}
            tableAlertOptionRender={({ selectedRowKeys }) => {
              return (
                <Space size={16}>
                  <a>批量删除</a>
                  <a>导出数据</a>
                </Space>
              );
            }}
          />
        </ProCard>
      </ProCard>
    </PageContainer>
  );
}
